package model

import (
	myConfig "common/config"
	"common/helper"
	myredis "common/redis"
	"common/userHelp"
	"database/sql"
	"errors"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
	"github.com/valyala/fasthttp"
	"strconv"
	"strings"
	"time"
)

type RedPackData struct {
	T int              `cbor:"t" json:"total"`
	D []RedPackCfgItem `cbor:"d" json:"d"`
}

type RedPackReceiveData struct {
	T int                  `cbor:"t" json:"total"`
	D []RedPackReceiveItem `cbor:"d" json:"d"`
	S RedPackStatistic     `cbor:"s" json:"s"`
}

type TurnTableReviewData struct {
	T int                   `cbor:"t" json:"total"`
	D []RurnTableReviewItem `cbor:"d" json:"d"`
}

type TurnTableHistoryData struct {
	T int                    `cbor:"t" json:"total"`
	D []RurnTableHistoryItem `cbor:"d" json:"d"`
}

type TurnTablePlayerData struct {
	T int                   `cbor:"t" json:"total"`
	D []RurnTablePlayerItem `cbor:"d" json:"d"`
}

type TurnTableMobileData struct {
	T int                   `cbor:"t" json:"total"`
	D []RurnTableMobileItem `cbor:"d" json:"d"`
}

type RedPackStatistic struct {
	ReceiveAmt float64 `json:"receive_amt" db:"receive_amt"`
	TotalAmt   float64 `json:"total_amt" db:"total_amt"`
	ReceiveNum int     `json:"receive_num" db:"receive_num"`
	TotalNum   int     `json:"total_num" db:"total_num"`
	CurrentAmt float64 `json:"current_amt" db:"current_amt"`
	CurrentNum float64 `json:"current_num" db:"current_num"`
}

type RurnTableHistoryItem struct {
	Id           int     `json:"id" db:"id"`
	Uid          int     `json:"uid" db:"uid"`                     // 用户ID
	Amount       float64 `json:"amount" db:"amount"`               // 奖励金额
	BeforeAmount float64 `json:"before_amount" db:"before_amount"` // 账变前的金额
	AfterAmount  float64 `json:"after_amount" db:"after_amount"`   // 账变后的金额
	CreatedAt    int64   `json:"created_at" db:"created_at"`
	Type         int     `json:"type" db:"type"` // 增加类型 1 大随机金额 2 小随机金额 3 1000元 4 50元 5 1元 6 获得随机次数 7 直接领奖 8 无奖励 9 后台增加
	Remark       string  `json:"remark" db:"remark"`
}

type RurnTableReviewItem struct {
	Id           int     `json:"id" db:"id"`
	Uid          int     `json:"uid" db:"uid"`                     // 申请人uid
	Username     string  `json:"username" db:"username"`           // 申请人
	Amount       float64 `json:"amount" db:"amount"`               // 领取金额
	ReviewRemark string  `json:"review_remark" db:"review_remark"` // 审核备注
	State        int     `json:"state" db:"state"`                 // 状态:1=审核中,2=审核通过,3=审核未通过
	ApplyAt      int64   `json:"apply_at" db:"apply_at"`           // 申请时间
	ReviewAt     int64   `json:"review_at" db:"review_at"`         // 审核时间
	ReviewUid    int     `json:"review_uid" db:"review_uid"`       // 审核人uid
	ReviewName   string  `json:"review_name" db:"review_name"`     // 审核人
}

type RurnTableMobileItem struct {
	Id    string `json:"id" db:"id"`
	Phone string `json:"phone" db:"phone"`
}

type RurnTablePlayerItem struct {
	Id          int     `json:"id" db:"id"`
	Uid         int     `json:"uid" db:"uid"`
	UnuseChance int     `json:"unuse_chance" db:"unuse_chance"`
	UsedChance  int     `json:"used_chance" db:"used_chance"`
	Amount      float64 `json:"amount" db:"amount"`
	HandAmount  float64 `json:"hand_amount" db:"hand_amount"`
	TotAmount   float64 `json:"tot_amount" db:"tot_amount"`
	Enabled     int     `json:"enabled" db:"enabled"`
	CreatedAt   int     `json:"created_at" db:"created_at"`
	UpdatedAt   int     `json:"updated_at" db:"updated_at"`
	RefreshTime int     `json:"refresh_time" db:"refresh_time"`
	AwardNum    int     `json:"award_num" db:"award_num"`
	Invite      int     `json:"invite" db:"invite"`
	CheckChance int     `json:"check_chance" db:"check_chance"`
}

func GetRedPackCfgList(param RedPackConfigParam) (RedPackData, error) {
	data := RedPackData{}
	where := "1=1"
	table := "tbl_cfg_redpack"
	join := ""
	oderBy := "id"
	oderType := "desc"
	if param.OrderBy != "" && param.OrderType != "" {
		oderBy = param.OrderBy
		oderType = param.OrderType
	}
	order := oderBy + " " + oderType
	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a where " + where
		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}
		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*"
	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func UpdateRedPackConfig(param RedPackCfgItem, isDelete int8) error {
	table := "tbl_cfg_redpack"
	query := ""
	if param.Id > 0 {
		if isDelete == 0 {
			if param.BeginDay != "" {
				BeginDay, _ := helper.TimeToLocDay(param.BeginDay, loc)
				param.BeginDay = strconv.Itoa(int(BeginDay))
			}
			if param.BeginDay != "" {
				EndDay, _ := helper.TimeToLocDay(param.EndDay, loc)
				param.EndDay = strconv.Itoa(int(EndDay))
			}
			query, _, _ = dialect.Update(table).Set(param).Where(g.Ex{"id": param.Id}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.Id}).ToSQL()
		}
	} else if param.Id < 0 {
		//query, _, _ = dialect.Update(table).Set(g.Ex{"status": param.Status}).ToSQL()
	} else {
		max_activeid := 100000
		newquery, _, _ := dialect.From("tbl_cfg_redpack").Select(g.COALESCE(g.MAX("activity_id"), 0)).ToSQL()
		err := meta.MerchantDB.Get(&max_activeid, newquery)
		if err != nil {
			return errors.New("数据库错误")
		}
		if max_activeid == 0 {
			max_activeid = 100000
		}
		param.ActivityId = max_activeid + 1
		BeginDay, _ := helper.TimeToLocDay(param.BeginDay, loc)
		param.BeginDay = strconv.Itoa(int(BeginDay))
		EndDay, _ := helper.TimeToLocDay(param.EndDay, loc)
		param.EndDay = strconv.Itoa(int(EndDay))
		query, _, _ = dialect.Insert(table).Rows(param).ToSQL()
	}
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

// 红包雨领取记录
func GetRedPackReceiveList(param RedPackConfigParam) (RedPackReceiveData, error) {
	data := RedPackReceiveData{}
	where := "1=1"
	table := "tbl_redpack_history"
	join := ""

	if param.StartTime != "" {
		StartTime, _ := helper.TimeToLocDay(param.StartTime, loc)
		where += " and created_at>='" + strconv.FormatInt(StartTime, 10) + "'"
	}
	if param.EndTime != "" {
		EndTime, _ := helper.TimeToLocDay(param.EndTime, loc)
		where += " and created_at<'" + (strconv.FormatInt(EndTime, 10)) + "'"
	}

	if param.Uid > 0 {
		where += " and uid=" + strconv.Itoa(param.Uid)
	}

	if param.ActivityId > 0 {
		where += " and activity_id=" + strconv.Itoa(param.ActivityId)
	}

	total_query := "select count(1) as current_num,ifnull(sum(amount),0) as current_amt from tbl_redpack_history where " + where
	err := meta.MerchantDB.Get(&data.S, total_query)
	if err != nil {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), 0), "数据库错误")
	}
	total_query = "select count(1) as receive_num,ifnull(sum(amount),0) as receive_amt from tbl_redpack_history"
	err = meta.MerchantDB.Get(&data.S, total_query)
	if err != nil {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), 0), "数据库错误")
	}

	total_query = "select ifnull(sum(redpack_num),0) as total_num,ifnull(sum(redpack_total_money),0) as total_amt from tbl_cfg_redpack"
	err = meta.MerchantDB.Get(&data.S, total_query)
	if err != nil {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), 0), "数据库错误")
	}

	oderBy := "id"
	oderType := "desc"
	if param.OrderBy != "" && param.OrderType != "" {
		oderBy = param.OrderBy
		oderType = param.OrderType
	}
	order := oderBy + " " + oderType
	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a where " + where
		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}
		if data.T == 0 {
			return data, nil
		}
	}

	field := "a.*"
	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)
	err = meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

// pdd转盘申请记录
func GetTurnTableReviewList(param RedPackConfigParam, IsReview int) (TurnTableReviewData, error) {
	data := TurnTableReviewData{}
	where := "1=1"
	table := "tbl_pdd_turntable_review"
	join := ""

	if param.StartTime != "" {
		StartTime, _ := helper.TimeToLocDay(param.StartTime, loc)
		where += " and apply_at>='" + strconv.FormatInt(StartTime, 10) + "'"
	}
	if param.EndTime != "" {
		EndTime, _ := helper.TimeToLocDay(param.EndTime, loc)
		where += " and apply_at<'" + (strconv.FormatInt(EndTime, 10)) + "'"
	}

	if param.Uid > 0 {
		where += " and uid=" + strconv.Itoa(param.Uid)
	}

	if param.OperatorId > 0 {
		where += " and review_uid=" + strconv.Itoa(param.OperatorId)
	}

	if IsReview == 1 {
		where += " and state=2 "
	} else if IsReview == 0 {
		where += " and state=1 "
	}

	oderBy := "id"
	oderType := "desc"
	if param.OrderBy != "" && param.OrderType != "" {
		oderBy = param.OrderBy
		oderType = param.OrderType
	}
	order := oderBy + " " + oderType
	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a where " + where
		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}
		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*"
	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)
	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func GetTurnTablePlayerInfo(param RedPackConfigParam) (TurnTablePlayerData, error) {
	data := TurnTablePlayerData{}
	where := "1=1"
	table := "tbl_pdd_turntable_info"
	join := ""

	if param.MinAmt >= 0 {
		where += " and amount>=" + strconv.Itoa(param.MinAmt)
	}
	if param.MaxAmt > 0 {
		where += " and amount<" + strconv.Itoa(param.MaxAmt)
	}

	if param.Uid > 0 {
		where += " and uid=" + strconv.Itoa(param.Uid)
	}

	oderBy := "id"
	oderType := "desc"
	if param.OrderBy != "" && param.OrderType != "" {
		oderBy = param.OrderBy
		oderType = param.OrderType
	}
	order := oderBy + " " + oderType
	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a where " + where
		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}
		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*"
	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)
	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

// 转盘领取物品
func GetTurnTableHistoryList(param RedPackConfigParam) (TurnTableHistoryData, error) {
	data := TurnTableHistoryData{}
	where := "1=1"
	table := "tbl_pdd_turntable_history"
	join := ""

	if param.StartTime != "" {
		StartTime, _ := helper.TimeToLocDay(param.StartTime, loc)
		where += " and created_at>='" + strconv.FormatInt(StartTime, 10) + "'"
	}
	if param.EndTime != "" {
		EndTime, _ := helper.TimeToLocDay(param.EndTime, loc)
		where += " and created_at<'" + (strconv.FormatInt(EndTime, 10)) + "'"
	}

	if param.Uid > 0 {
		where += " and uid=" + strconv.Itoa(param.Uid)
	}

	//增加类型 1 大随机金额 2 小随机金额 3 1000元 4 50元 5 1元 6 获得随机次数 7 直接领奖 8 无奖励 9 后台增加
	if param.GetType > 0 {
		where += " and type in(" + strconv.Itoa(param.GetType) + ")"
	}
	oderBy := "id"
	oderType := "desc"
	order := oderBy + " " + oderType
	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a where " + where
		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}
		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*"
	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)
	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func TurnTablecheck(id, state int, adminid, adminname string) error {
	TurnTableItem := RurnTableReviewItem{}
	query, _, _ := dialect.From("tbl_pdd_turntable_review").Where(g.Ex{"id": id}).Limit(1).ToSQL()
	err := meta.MerchantDB.Get(&TurnTableItem, query)
	if err != nil {
		return errors.New("数据库错误")
	}

	if TurnTableItem.State != 1 {
		return errors.New(helper.OrderStateErr)
	}
	if state != 2 && state != 3 {
		return errors.New("参数错误")
	}
	//先改状态再加钱
	tx, err := meta.MerchantDB.Begin()
	Record := g.Record{
		"state":       state,
		"review_at":   time.Now().Unix(),
		"review_uid":  adminid,
		"review_name": adminname,
	}
	query, _, _ = dialect.Update("tbl_pdd_turntable_review").Set(Record).Where(g.Ex{"id": id}).ToSQL()
	_, err = tx.Exec(query)
	if err != nil {
		tx.Rollback()
		return pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	if state == 2 {
		uid := strconv.Itoa(TurnTableItem.Uid)
		ret, err := UpdateBalance(uid, TurnTableItem.Amount, helper.TransactionTruntableUpPoint, strconv.Itoa(TurnTableItem.Id))
		if ret == false {
			tx.Rollback()
			return pushLog(err, "数据库错误")
		}
	}
	tx.Commit()
	return nil

}

// 分享号码列表
func GetTurnTableMobileList(param RedPackConfigParam) (TurnTableMobileData, error) {
	data := TurnTableMobileData{}
	where := "1=1"
	table := "tbl_cfg_pdd_turntable_phone"
	join := ""

	if param.Mobile != "" {
		where += " and phone=" + param.Mobile
	}

	oderBy := "id"
	oderType := "desc"
	order := oderBy + " " + oderType
	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a where " + where
		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}
		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*"
	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)
	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

func TurnTablePhoneAdd(phone string) error {
	phone_number := strings.Split(phone, ",")
	if len(phone_number) == 0 {
		return errors.New(helper.IDErr)
	}
	for _, value := range phone_number {
		if value != "" {
			count := 0
			query, _, _ := dialect.From("tbl_cfg_pdd_turntable_phone").Select(g.COUNT("id")).Where(g.Ex{"phone": value}).ToSQL()
			err := meta.MerchantDB.Get(&count, query)
			if err != nil {
				continue
			}
			if count > 0 {
				continue
			}
			query, _, _ = dialect.Insert("tbl_cfg_pdd_turntable_phone").Rows(g.Record{"phone": value}).ToSQL()
			_, err = meta.MerchantDB.Exec(query)
			if err != nil {
				continue
			}
		}
	}
	return nil
}

func TurnTablePhoneDelete(id string) error {
	ids := strings.Split(id, ",")
	if len(ids) == 0 {
		return errors.New(helper.IDErr)
	}
	for _, value := range ids {
		if value != "" {
			query, _, _ := dialect.Delete("tbl_cfg_pdd_turntable_phone").Where(g.Ex{"id": value}).ToSQL()
			_, err := meta.MerchantDB.Exec(query)
			if err != nil {
				continue
			}
		}
	}
	return nil
}

func TurnTablePhoneClear() error {
	query := "truncate table tbl_cfg_pdd_turntable_phone"
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

func TurnTableSetExtramt(uid int, amount float64) error {
	userHelp.LoadUserToRedis(strconv.Itoa(uid))
	state := myredis.AddUserFieldValueByFloat64(strconv.Itoa(uid), myConfig.G_tbl_pdd_turntable_info+"hand_amount", amount)
	if !state {
		return errors.New(helper.RedisErr)
	}
	return nil
}

func TurnTableSetTimes(uid int, times int) error {
	userHelp.LoadUserToRedis(strconv.Itoa(uid))
	state := myredis.AddUserFieldValueByInt64(strconv.Itoa(uid), myConfig.G_tbl_pdd_turntable_info+"unuse_chance", int64(times))
	if !state {
		return errors.New(helper.RedisErr)
	}
	return nil
}

// 转盘值配置
type TblTurntableConfig struct {
	Id         int     `db:"id" json:"id"`
	Type       int     `db:"type" json:"type"`
	LuckyPoint float64 `db:"lucky_point" json:"lucky_point"`
	Rate       float64 `db:"rate" json:"rate"`
}

func GetTurntableConfig(param TblTurntableConfig) ([]TblTurntableConfig, error) {
	data := []TblTurntableConfig{}

	query := "select * from tbl_cfg_turntable where type=" + strconv.Itoa(param.Type) + " order by id asc"
	err := meta.MerchantDB.Select(&data, query)
	if err != nil && err != sql.ErrNoRows {

		return data, err
	}
	return data, nil
}

func UpdateTurntableConfig(param TblTurntableConfig, isDelete int8) error {
	table := "tbl_cfg_turntable"
	query := ""
	record := g.Record{
		"type":        param.Type,
		"lucky_point": param.LuckyPoint,
		"rate":        param.Rate,
	}
	if param.Id > 0 {
		if isDelete == 0 {
			query, _, _ = dialect.Update(table).Set(record).Where(g.Ex{"id": param.Id}).ToSQL()
		} else {
			query, _, _ = dialect.Delete(table).Where(g.Ex{"id": param.Id}).ToSQL()
		}
	} else {
		query, _, _ = dialect.Insert(table).Rows(record).ToSQL()
	}

	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return errors.New("数据库错误")
	}
	return nil
}

// 转盘活动数据参数
type TurntableCommiParam struct {
	Uid      int    `json:"uid"`
	Type     int    `json:"type"`
	Page     int    `json:"page"`
	PageSize int    `json:"page_size"`
	OderBY   string `json:"order_by"`
	OderType string `json:"order_type"`
}

// 转盘活动数据 响应数据
type TurntableCommiRetData struct {
	T int                  `cbor:"t" json:"total"`
	D []TurntableCommiData `cbor:"d" json:"d"`
}

// 转盘活动数据
type TurntableCommiData struct {
	Uid        int    `json:"uid" db:"uid"`
	OperatorId string `json:"operator_id" db:"operator_id"`
	BusinessId string `json:"business_id" db:"business_id"`
	ThisAward  string `json:"this_award" db:"this_award"`
	LastAward  string `json:"last_award" db:"last_award"`
	TotalAward string `json:"total_award" db:"total_award"`
}

func TurntableComiList(param TurntableCommiParam, ctx *fasthttp.RequestCtx) (TurntableCommiRetData, error) {
	data := TurntableCommiRetData{}
	table := "tbl_member_base"
	where := "1=1"
	oderBy := "uid"
	oderType := "desc"

	//本周开始时间戳
	now := time.Now()

	//日活动数据
	dailyStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).Unix()
	yes := now.AddDate(0, 0, -1)
	lastDailyStartDate := time.Date(yes.Year(), yes.Month(), yes.Day(), 0, 0, 0, 0, yes.Location()).Unix()

	//获取今日
	query1 := fmt.Sprintf("select uid,sum(award) this_award from tbl_rec_turntable where "+" created_at>='%d' group by uid", dailyStart)
	//获取昨日
	query2 := fmt.Sprintf("select uid,sum(award) last_award from tbl_rec_turntable where "+" created_at>='%d' and created_at<'%d' group by uid", lastDailyStartDate, dailyStart)
	query3 := "select uid,sum(award) total_award from tbl_rec_turntable group by uid"

	query := "select mb.uid,mb.operator_id,mb.business_id,ifnull(aa.this_award,0) this_award,ifnull(bb.last_award,0) last_award,ifnull(cc.total_award,0) total_award  from " + table + " as mb " +
		" left join (" + query1 + ") as aa on aa.uid=mb.uid" +
		" left join (" + query2 + ") as bb on bb.uid=mb.uid" +
		" left join (" + query3 + ") as cc on cc.uid=mb.uid"

	queryTable := "(" + query + " where mb.tester=1 )"

	if param.Uid != 0 {
		where += " and a.uid=" + strconv.Itoa(param.Uid)
	}
	if param.Type > 0 {
		where += " and a.type=" + strconv.Itoa(param.Type)
	}
	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}

	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		where += " and c.id=" + loginUser.Operator
	}
	if loginUser.Businsess != "" {
		where += " and d.id=" + loginUser.Businsess
	}

	join := " left join tbl_operator_info as c on c.id=a.operator_id" //渠道表
	join += " left join tbl_business_info as d on d.id=a.business_id" //业务员表

	order := oderBy + " " + oderType

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a " + join + " where a.tester=1 and " + where
		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}
	field := "a.*"

	query = "select " + field + " from " + queryTable + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {

		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}
